package com.talkyun.utils;

import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

public class HttpUtils {
    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public static final String HTTP_HEADER_MD5 = "Content-MD5";
    private static final String DEF_CHARSET = "utf-8";
    private String url;
    private int timeout;
    private boolean keepAlive = false;

    public HttpUtils(String url, int timeout) {
        this.url = url;
        this.timeout = timeout;
    }

    public HttpUtils(String url, int timeout, boolean keepAlive) {
        this.url = url;
        this.timeout = timeout;
        this.keepAlive = keepAlive;
    }

    public String get() throws IOException {
        return this.handle("GET", null);
    }

    public String post(String body) throws IOException {
        return this.handle("POST", body);
    }

    public String head(String header) throws IOException {
        URL url2 = new URL(url);
        HttpURLConnection conn = isHttps(url2) ? getHttpsConn(url2) : (HttpURLConnection) url2.openConnection();

        conn.setRequestMethod("HEAD");
        conn.setReadTimeout(timeout);
        conn.setConnectTimeout(timeout);
        if (conn.getResponseCode() != 200) {
            throw new IOException("Http response code error! " + conn.getResponseCode());
        } else {
            Map<String, List<String>> hs = conn.getHeaderFields();
            List<String> list = hs.get(header);
            return list != null && !list.isEmpty() ? list.get(0) : null;
        }
    }

    private String handle(String method, String body) throws IOException {
        URL url2 = new URL(url);
        HttpURLConnection conn = isHttps(url2) ? getHttpsConn(url2) : (HttpURLConnection) url2.openConnection();

        // socket settings
        conn.setRequestMethod(method);
        if (!"GET".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
        }
        conn.setDoInput(true);
        conn.setReadTimeout(timeout);
        conn.setConnectTimeout(timeout);
        conn.setUseCaches(false);
        if (keepAlive) {
            conn.setRequestProperty("Connection", "Keep-Alive");
        } else {
            conn.setRequestProperty("Connection", "Close");
        }

        // write body
        if (body != null && body.trim().length() != 0) {
            byte[] data = body.getBytes(DEF_CHARSET);
            conn.setRequestProperty("Content-Type", "application/json; charset=" + DEF_CHARSET);
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            conn.getOutputStream().write(data);
        }

        int status = conn.getResponseCode();
        if (status == 200) {
            return this.doRead(conn.getInputStream());
        } else {
            throw new IOException(this.doRead(conn.getErrorStream()));
        }
    }

    private HttpsURLConnection getHttpsConn(URL url) {
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String doRead(InputStream is) throws IOException {
        byte[] buf = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream(4 * 1024);
        for (int num; (num = is.read(buf)) != -1; ) {
            baos.write(buf, 0, num);
        }
        return baos.toString(DEF_CHARSET);
    }

    private boolean isHttps(URL url) {
        return url.getProtocol().equalsIgnoreCase("https");
    }
}